//
//  EFAReportVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/8/6.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAReportVC.h"
#import "EFADevInfoTCell.h"
#import "EFADevInfoChartTCell.h"
#import "EFAReportTCell.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFAModel.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFARptPreviewTCell.h"
#import "EFARptPreTypeTCell.h"
#import "EFARptSelDateVC.h"
#import "NSDate+XDTimerFormatter.h"

@interface EFAReportVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak,   nonatomic) IBOutlet UILabel *hTypeLabel;
@property (weak,   nonatomic) IBOutlet UILabel *hDateLabel;
@property (weak,   nonatomic) IBOutlet UIButton *hDateBtn;

@property (strong, nonatomic) UIBarButtonItem *dateBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer

@property (nonatomic, strong) NSDate *curDate;      //!< 只是用来计算初始化的起始和结束时间
@property (nonatomic, assign) EFARptType rptType;   //!< 报表类型
@property (nonatomic, strong) NSDate *startDate;    //!< 时间段的起始时间
@property (nonatomic, strong) NSDate *endDate;      //!< 时间段的结束时间
@property (nonatomic,   copy) NSString *rptPrompt;  //!< 报表标题

@property (strong, nonatomic) EFARptModel *rptModel; //!< 报表的模型

@end

static NSString *const kReuseTitleCellId = @"EFADevInfoTCell";
static NSString *const kReuseChartCellId = @"EFADevInfoChartTCell";
static NSString *const kReuseReportDetailId = @"EFAReportTCell";
static NSString *const kReuseReportPreviewId = @"EFARptPreviewTCell";
static NSString *const kReuseReportPreTypeId = @"EFARptPreTypeTCell";

@implementation EFAReportVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.project_name;
//    self.navigationItem.rightBarButtonItems = @[self.dateBarBtnItem];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    self.hTypeLabel.text = nil;
    self.hDateLabel.text = nil;
    [self.hDateBtn addTarget:self action:@selector(hDateBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.headerBgView;
    
    UINib *titleNib = [UINib nibWithNibName:kReuseTitleCellId bundle:nil];
    [self.tableView registerNib:titleNib forCellReuseIdentifier:kReuseTitleCellId];
    UINib *chartNib = [UINib nibWithNibName:kReuseChartCellId bundle:nil];
    [self.tableView registerNib:chartNib forCellReuseIdentifier:kReuseChartCellId];
    UINib *reportNib = [UINib nibWithNibName:kReuseReportDetailId bundle:nil];
    [self.tableView registerNib:reportNib forCellReuseIdentifier:kReuseReportDetailId];
    UINib *preNib = [UINib nibWithNibName:kReuseReportPreviewId bundle:nil];
    [self.tableView registerNib:preNib forCellReuseIdentifier:kReuseReportPreviewId];
    UINib *preTypeNib = [UINib nibWithNibName:kReuseReportPreTypeId bundle:nil];
    [self.tableView registerNib:preTypeNib forCellReuseIdentifier:kReuseReportPreTypeId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 252.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"暂无数据" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.rptModel ? 3 + self.rptModel.alarm_scale_map_list.count : 0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1 + self.rptModel.overview.overview_analyze_list.count + 1;
    }
    return 1;   // 一种参量类型是一个表格
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {   // 预览图
        if (indexPath.row == 0) {
            EFARptPreviewTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseReportPreviewId forIndexPath:indexPath];
            [cell configViewWithRptOverView:self.rptModel.overview];
            return cell;
        } else {
            EFARptPreTypeTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseReportPreTypeId forIndexPath:indexPath];
            EFARptOviAnaItem * item = nil;
            NSInteger index = indexPath.row - 2;
            if (index >= 0 && index < self.rptModel.overview.overview_analyze_list.count) {
                item = self.rptModel.overview.overview_analyze_list[index];
            }
            [cell configViewWithOviAnaItem:item];
            return cell;
        }
    } else if (indexPath.section > 0 && indexPath.section < (1 + self.rptModel.alarm_scale_map_list.count)) {
        EFADevInfoChartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseChartCellId forIndexPath:indexPath];
        if ((indexPath.section - 1) < self.rptModel.alarm_scale_map_list.count) {
            [cell configViewWithRptAlarmScaleItem:self.rptModel.alarm_scale_map_list[indexPath.section - 1]];
        }
        return cell;
    } else if (indexPath.section == (3 + self.rptModel.alarm_scale_map_list.count - 2)) {
        EFADevInfoChartTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseChartCellId forIndexPath:indexPath];
        [cell configViewWithRptModel:self.rptModel rptType:self.rptType];
        return cell;
    }
    EFAReportTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseReportDetailId forIndexPath:indexPath];
    NSString * reportStr = [NSString stringWithFormat:@"该单位（%@）%@", self.rptPrompt, self.rptModel.reportDescribe];
    [cell configViewWithString:reportStr];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[EFARptPreviewTCell class]]) {
        [(EFARptPreviewTCell *)cell startAnimation];
    }
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell isKindOfClass:[EFARptPreviewTCell class]]) {
        [(EFARptPreviewTCell *)cell stopAnimation];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 12.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
//    [self jumpToMsgCtrl];
}

#pragma mark - event response
- (void)hDateBtnTapped:(UIButton *)btn {
    EFARptSelDateVC *vc = [[EFARptSelDateVC alloc] init];
    vc.selDateInit = self.startDate;
    vc.reportTypeInit = self.rptType;
    vc.successHandle = ^(EFARptType type, NSDate *startDate, NSDate *endDate, NSString *prompt) {
        self.startDate = startDate;
        self.endDate = endDate;
        self.rptType = type;
        self.rptPrompt = prompt;
        [self.tableView.mj_header beginRefreshing];
    };
    [self presentViewController:vc animated:YES completion:nil];
}
- (void)dateBarBtnItemTapped:(UIBarButtonItem *)item {
    EFARptSelDateVC *vc = [[EFARptSelDateVC alloc] init];
    [self presentViewController:vc animated:YES completion:nil];
}
//- (void)controlBarBtnItemTapped:(UIBarButtonItem *)item {
//    UIStoryboard *mainSb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
//    EFAMsgControlCVC *vc = [mainSb instantiateViewControllerWithIdentifier:@"EFAMsgControlCVC"];
//    vc.device_id = self.deviceId;
//    vc.device_name = self.device_name;
//    [self showViewController:vc sender:nil];
//}
#pragma mark - private methods
- (void)jumpToMsgCtrl {
    //    EFAMsgControlVC *vc = [[EFAMsgControlVC alloc] init];
    //    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    NSArray *array = @[@"日报", @"周报", @"月报", @"季报", @"年报"];
    if (self.rptType < array.count) {
        self.hTypeLabel.text = array[self.rptType];
    }
    self.hDateLabel.text = self.rptPrompt;
    [self.tableView reloadData];
}
- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}
- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDeviceInfoWithHeader:isHeader];
}
#pragma mark - network request
- (void)requestDeviceInfoWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairyproject_id" : @(self.project_id),
                           @"start_time" : [self.startDate xd_yyyy_MM_ddHHmmss],
                           @"end_time" : [self.endDate xd_yyyy_MM_ddHHmmss]};
    NSLog(@"报表请求参数%@", pars);
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiReport] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求报表信息返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        self.rptModel = [EFARptModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求报表信息失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (NSDate *)curDate {
    if (!_curDate) {
        NSDate *nowDate = [NSDate date];
        NSDateComponents *com = [[NSDateComponents alloc] init];
        com.day = -1;
        _curDate = [[NSCalendar currentCalendar] dateByAddingComponents:com toDate:nowDate options:NSCalendarMatchStrictly];
    }
    return _curDate;
}
- (NSDate *)startDate {
    if (!_startDate) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *com = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.curDate];
        _startDate = [calendar dateWithEra:1 year:com.year month:com.month day:com.day hour:0 minute:0 second:0 nanosecond:0];
    }
    return _startDate;
}
- (NSDate *)endDate {
    if (!_endDate) {
        NSCalendar *calendar = [NSCalendar currentCalendar];
        NSDateComponents *com = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:self.curDate];
        _endDate = [calendar dateWithEra:1 year:com.year month:com.month day:com.day hour:23 minute:59 second:59 nanosecond:0];
    }
    return _endDate;
}
- (NSString *)rptPrompt {
    if (!_rptPrompt) {
        _rptPrompt = [self.curDate xd_yyyy__MM__dd];
    }
    return _rptPrompt;
}

- (UIBarButtonItem *)dateBarBtnItem {
    if (!_dateBarBtnItem) {
        _dateBarBtnItem = [[UIBarButtonItem alloc] initWithTitle:@"2017/08" style:UIBarButtonItemStylePlain target:self action:@selector(dateBarBtnItemTapped:)];
    }
    return _dateBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

@end
